<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <el-input v-model="query.title" clearable placeholder="输入搜索产品名称" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
      <el-input v-model="query.smallTitle" clearable placeholder="输入搜索标题" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery" />
      <el-select v-model="query.color"  clearable placeholder="请选中颜色" class="filter-item" style="width: 200px">
        <el-option v-for="item in colorList" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>

      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
      <!-- 新增 -->
      <el-button
        v-permission="['admin','atBusiness:add']"
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >新增</el-button>
      <el-button
        type="danger"
        class="filter-item"
        size="mini"
        icon="el-icon-refresh"
        @click="toQuery"
      >刷新</el-button>
      <!--表单组件-->
      <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="title" width="800px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="主题">
            <el-input v-model="form.title" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="小标题">
            <el-input v-model="form.smallTitle" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="卡号前缀">
            <el-input v-model="form.prefix" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="主图">
           <MaterialList v-model="form.mainUrlArr" style="width: 300px" type="image" :num="1" :width="150" :height="150" />

          </el-form-item>
          <el-form-item label="轮播图">
            <MaterialList v-model="form.urlsArr" type="image" :num="5" :width="150" :height="150" />
          </el-form-item>
          <el-form-item label="颜色">
            <el-select v-model="form.color" clearable placeholder="请选中颜色" class="filter-item" style="width: 370px">
              <el-option v-for="item in colorList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="积分">
            <el-input v-model="form.points" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input v-model="form.sort" style="width: 370px;" type="number"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="生成数量">
            <el-input v-model="form.totalNum" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="cancel">取消</el-button>
          <el-button :loading="loading" type="primary" @click="submit">批量生成卡片</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table v-loading="loading" :data="data" size="small" style="width: 100%;align-items: center;">
        <el-table-column type="selection" width="55" />
        <el-table-column  prop="id" label="主键" />
        <el-table-column  prop="title" label="主题" />
        <el-table-column prop="smallTitle" label="小标题" />
        <el-table-column prop="prefix" label="卡号前缀" />
        <el-table-column prop="mainUrl" label="主图" >
           <template slot-scope="scope">
               <el-image
                     style="width: 80px; height: 80px"
                     :src="scope.row.mainUrl"
                     :preview-src-list="[scope.row.mainUrl]"
                   ></el-image>
            </template>
        </el-table-column>
        <!-- <el-table-column  prop="urls" label="轮播图" /> -->
        <el-table-column  prop="color" label="颜色" />
        <!-- <el-table-column prop="points" label="积分" /> -->
        <el-table-column  prop="points" label="积分" >
          <template slot-scope="scope">
              <span>{{formatPoints(scope.row.points)}}</span>
           </template>
         </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="totalNum" label="总数" />
        <el-table-column prop="registerNum" label="登记数" />
        <el-table-column prop="noRegisterNum" label="未登记数" />
        <el-table-column prop="createTime" label="添加时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
         <el-table-column prop="sort" label="排序值" />
        <el-table-column prop="updateTime" label="更新时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','hcsCard:edit','hcsCard:del']" label="操作" width="300px" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="edit(scope.row)"
            >
              编辑
            </el-button>
            <el-popover
              :ref="scope.row.id"
              placement="top"
              width="180"
            >
              <p>确定删除本条数据吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
              </div>
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page="page + 1"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>

<script>

  import initData from '@/mixins/crud'
  import checkPermission from '@/utils/permission'
  import { add, edit,del } from '@/api/hcsCard'

  import picUpload from '@/components/pic-upload'
  import MaterialList from '@/components/material'
  import UeditorWrap from 'vue-ueditor-wrap';


export default {
  mixins: [initData],
   components: { picUpload, MaterialList,UeditorWrap },
  data() {
    return {
      isAdd:true,
       loading: false, dialog: false,
       delLoading: false,
       title:"新增",
       form:{
         id: '',
         title :"",
         smallTitle: "",
         mainUrl :"",
         mainUrlArr: [],
         urls:"",
         urlsArr :[],
         color: '',
         totalNum:'',
         points:0,
         remark:"",
         sort:''
      },
      colorList:[
        {name:'原色',value:"原色"}, {name:'异色',value:"异色"}, {name:'特殊色',value:"特殊色"}
      ],
      statusList:[
        {name:'下架',value:0}, {name:'已上架',value:1}
      ],
      permission: {
        add: ['admin', 'hcsCard:add'],
        edit: ['admin', 'hcsCard:edit'],
        del: ['admin', 'hcsCard:del']
      },
      rules: {
      },
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: '100%', // 初始容器宽度
        UEDITOR_HOME_URL: '/UEditor/',
        serverUrl: ''
      }
      }
  },
  created() {
    this.$nextTick(() => {
      this.init()
    })
  },
  watch: {
    'form.mainUrlArr': function(val) {
      if (val) {
        this.form.mainUrl = val.join(',')
      }
    }, 'form.urlsArr': function(val) {
      if (val) {
        this.form.urls = val.join(',')
      }
    }
  },
  methods: {
   checkPermission,
   beforeInit() {
     this.url = 'api/hcsCard'
     const sort = 'id,desc'
     this.params = { page: this.page, size: this.size, sort: sort }
     return true
   },

   add(){
     this.dialog = true
     this.isAdd = true
     // this.resetForm()
   },
   submit(){
     this.loading = true
     if (this.isAdd) {
       this.doAdd()
     } else this.doEdit()
   },
   refresh(){
     this.dialog = false
     this.form = {
      id: '',
      businessName :"",
      status: 0,
      remark:""
     }
   },
   addCustomDialog () {
     window.UE.registerUI('yshop', function (editor, uiName) {
       let dialog = new window.UE.ui.Dialog({
         iframeUrl: '/yshop/materia/index',
         editor: editor,
         name: uiName,
         title: '上传图片',
         cssRules: 'width:1200px;height:500px;padding:20px;'
       });
       this.dialog = dialog;

       var btn = new window.UE.ui.Button({
         name: 'dialog-button',
         title: '上传图片',
         cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
         onclick: function () {
           dialog.render();
           dialog.open();
         }
       });

       return btn;
     }, 37);
   },
   cancel(){
     this.refresh()
     this.init()
   },
   doAdd() {
     this.title = "新增"
     this.form.points = this.form.points*10
     add(this.form).then(res => {
       this.refresh()
       this.$notify({
         title: '添加成功',
         type: 'success',
         duration: 2500
       })
       this.loading = false
       this.init()
     }).catch(err => {
       this.loading = false
       console.log(err.response.data.message)
     })
   },
   formatPoints(points) {
         return points / 10;
   },
   doEdit() {
    this.form.points = this.form.points*10
     edit(this.form).then(res => {
       this.refresh()
       this.$notify({
         title: '修改成功',
         type: 'success',
         duration: 2500
       })
       this.loading = false
       this.init()
     }).catch(err => {
       this.loading = false
       console.log(err.response.data.message)
     })
   },
   subDelete(id){
     this.delLoading = true
     let ids = [id]
     del(ids).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
       this.init()
     }).catch(err => {
       this.loading = false
     })
   },
   edit(data) {
     this.title = "编辑"
     this.isAdd = false
     this.form = {
       id: data.id,
       title: data.title,
       smallTitle: data.smallTitle,
       mainUrl: data.mainUrl,
       mainUrlArr:data.mainUrl ? data.mainUrl.split(',') : [],
       urls: data.urls,
       urlsArr:data.urls ? data.urls.split(',') : [],
       totalNum: 0,
       color: data.color,
       points: data.points/10,
       remark: data.remark,
       sort:data.sort
     }
     this.dialog = true
   }
  }
}



</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
</style>
